import tkinter as tk
from tkinter import messagebox
from datetime import datetime


def purchase():
    now = datetime.now()

    # 商品信息
    products = [
        {"name": "Coca-Cola", "price": 3},
        {"name": "Iced Tea", "price": 4},
        {"name": "Sprite", "price": 3},
        {"name": "Lays", "price": 5},
        {"name": "Master Kang", "price": 3},
        {"name": "Oreo", "price": 3},
        {"name": "Choclairs", "price": 3},
        {"name": "Weilong", "price": 4},
        {"name": "Nongfu Spring Water", "price": 2}
    ]

    # 创建主窗口
    window = tk.Tk()
    window.title("Shopping interface")

    # 创建商品列表
    product_list = tk.Listbox(window, width=30)
    for product in products:
        product_list.insert(tk.END, f"{product['name']}: ¥{product['price']:.2f}")
    product_list.pack(pady=10)

    def payment1():  # 跳出付款界面
        selected_index = product_list.curselection()
        if not selected_index:
            messagebox.showwarning("Warning", "Select at least one!")
        else:
            # 创建支付窗口
            payment_window = tk.Toplevel(window)
            payment_window.title("Payment and Storage Interface")
            payment_window.geometry("200x100")

            # 获取选定的商品
            selected_index = product_list.curselection()[0]
            product = products[selected_index]
            quantity = int(quantity_entry.get())
            price = product["price"] * quantity  # 计算价格（数量乘以单价）

            # 创建“支付”按钮
            def payment2():  # 支付

                with open("balance.txt", "r", encoding="utf-8") as f:
                    content = f.read().strip()
                    number = float(content)
                    result = number - float(price)
                if result < 0:
                    raise ValueError("Insufficient balance, please recharge and try again!")

                with open("balance.txt", "w", encoding="utf-8") as f:
                    f.write(str(result))

                comment = entry.get()
                with open("history.txt", "a", encoding="utf-8") as f:
                    content = f"Time: {now}, Goods: {product['name']}, Quantity: {quantity}, Amount: {price}, Comment: {comment}\n"
                    f.write(content)

                # 显示支付成功的提示
                success_window = tk.Toplevel(payment_window)
                success_window.title("Payment Success!")
                success_window.geometry("200x50")
                label = tk.Label(success_window, text="Payment Success!")
                label.pack()
                success_window.mainloop()

            label1 = tk.Label(payment_window, text=f"You need to pay {price} yuan.")
            label1.pack()
            label2 = tk.Label(payment_window, text="Add a comment!")
            label2.pack()
            entry = tk.Entry(payment_window)
            entry.pack()
            button1 = tk.Button(payment_window, text="Pay", command=payment2)
            button1.pack()

    # 创建数量输入框
    quantity_label = tk.Label(window, text="Number")
    quantity_label.pack()
    quantity_entry = tk.Entry(window, width=5)
    quantity_entry.pack()

    # 创建“支付”按钮
    add_button = tk.Button(window, text="Pay", command=payment1)
    add_button.pack(pady=10)

    # 运行主循环
    window.mainloop()


if __name__ == "__main__":
    purchase()






